<script setup>
import {
  reactive,
  computed,
  ref,
  h,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  createVNode,
} from "vue";

import {
  CloseOutlined,
  CheckOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
} from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import request from "@/common/utils/request";

import Ai_style from "./Component/Ai_style.vue";

import { Modal } from "ant-design-vue";

import { message } from "ant-design-vue";

import EditAiText from "./Component/EditAiText.vue";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";
const copyLibraryModal = ref(null);

const route = useRoute();
const router = useRouter();
const emit = defineEmits(["getTemplateData:modelData", "cancel"]);

const props = defineProps({
  aiModelList: {
    type: Array,
    default: () => [],
  },
});

const state = reactive({
  visible: false,
  currentId: "",
  // ai配图, 截取的图片数量
  sliceNum: 10,
  text: "",
  // 抽屉中的详情数据
  detailData: {},
  /*
          inspiration_text_id -- 本项文案id
          unique_id -- 唯一id
         */
  queryData: {},
  // loding
  spinning: false,
});

// 加载中 icon
const indicator = h(LoadingOutlined, {
  style: {
    fontSize: "34px",
    marginTop: "-37px",
    marginLeft: "-18px",
  },
  spin: true,
});

// 模板广场页面带过来的 信息
const queryData = computed(() => {
  return {
    viewType: route.query?.viewType, // 1模板详情, 2混剪详情
    isAi: route.query?.isAi, // true 为ai页面过来的
    id: route.query?.id, // 详情id
    unique_id: route.query?.unique_id, // 爆破款文案库使用时,请求详情携带的唯一id
  };
});

// 编辑文案弹窗
const EditAiTextRef = ref(null);

// 编辑文案
const editText = (record) => {
  // 更新所需参数
  const params = {
    scene_des: record.scene_des,
    subtitle_content: record.subtitle_content,
    inspiration_text_id: state.queryData.inspiration_text_id,
    unique_id: state.queryData.unique_id,
    id: record.id,
  };
  // 打开抽屉 传递参数
  EditAiTextRef.value && EditAiTextRef.value.open(params);
};

// 删除某条字幕
const deletText = async (id) => {
  const res = await request.del(
    "work_ai",
    "/user/shotstack/inspirationText/split/delete",
    {
      inspiration_text_id: state.queryData.inspiration_text_id,
      unique_id: state.queryData.unique_id,
      id,
    }
  );
  getDetaile();
};

// 备份数据
const atherData = reactive({
  text: "",
});

// 优化后文案 table
const columns = reactive([
  {
    title: "字幕内容",
    dataIndex: "subtitle_content",
    key: "subtitle_content",
  },
  {
    title: "场景描述",
    dataIndex: "scene_des",
    key: "scene_des",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    width: 120,
  },
]);

// ai绘画模型列表组件
const Ai_styleRef = ref(null);

// 视频组 获取ai视频发送请求 需要的参数
const modelId = computed(() => {
  return Ai_styleRef.value?.requestData || {};
});

// 当前选择的风格名称
const selectCart_name = computed(() => {
  return Ai_styleRef.value?.selectCart_name || "";
});

const timeId = ref(null);

// 获取整体的详情或数据
const getDetaile = async (queryData = {}) => {
  state.spinning = true;
  Object.keys(queryData).length != 0 && (state.queryData = queryData);

  try {
    const { result } = await request.get(
      "work_ai",
      "/user/shotstack/inspirationTextUse/record/detail",
      {
        inspiration_text_id: state.queryData.inspiration_text_id,
        unique_id: state.queryData.unique_id,
      }
    );

    console.log(result, "详情数据============");
    if (result.process == "done") {
      if (result.fail_reason != "") {
        message.warning(result.fail_reason);
      }
      state.detailData = result;
      atherData.text = result.text;
      state.spinning = false;
      timeId.value && clearTimeout(timeId.value);
    } else {
      timeId.value = setTimeout(() => {
        getDetaile();
      }, 2000);
    }
  } catch (error) {
    state.spinning = false;
    console.log(error, "获取详情失败");
  }
};

// 重新解析原始文案
const reanalysis = async () => {
  if (atherData.text.trim().length < 30)
    return message.warning("文案不能少于30个字符！");
  const { result } = await request.put(
    "work_ai",
    "/user/shotstack/inspirationText/record/update",
    {
      inspiration_text_id: state.queryData.inspiration_text_id,
      unique_id: state.queryData.unique_id,
      text: atherData.text,
    }
  );
  console.log(result, "重新解析文本");
  getDetaile();
};

// 点击确定 emit 父组件调用接口获取模板内容
const submitConfirm = () => {
  if (!atherData.text) {
    return message.warning("文案不能为空");
  }
  if (!modelId.value.modelId) {
    return message.warning("请选择绘图风格!");
  }
  if (!state.detailData?.text_splits || !state.detailData?.text_splits.length) {
    return message.warning("当前文案列表为空, 请输入原始文案后重新解析!");
  }
  message.success("AI生图任务提交成功");
  emit("getTemplateData", modelId.value.modelId);
  state.visible = false;
};

const open = () => {
  state.visible = true;

  nextTick(() => {
    // 初始默认选中
    const id =
      props.aiModelList.find((ele) => ele.selected == 1)?.id ||
      props.aiModelList?.[0]?.id ||
      "";
    !!Ai_styleRef.value && Ai_styleRef.value.checkedFn(id);
  });
};

const close = () => {
  Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "当前AI生图功能还未进行保存, 关闭后数据不会保存和更新",
    cancelText: "确认返回",
    okText: "留在当前页",
    onOk: async () => {
      // 留在页面中
    },
    onCancel() {
      state.visible = false;
      router.back();
      // router.push({
      //   name: "FormworkSquareContent",
      // });
    },
  });
};

onUnmounted(() => {
  // 组件关闭结束轮询
  timeId.value && clearTimeout(timeId.value);
});
const styleList = computed(() => {
  return props.aiModelList.map((item) => {
    return {
      value: item.id,
      label: item.name,
    };
  });
});

// 文案库导入
const textImport = (type = "open") => {
  if (type == "open") {
    copyLibraryModal.value.showModal();
  } else {
    copyLibraryModal.value.closeModal();
  }
};

// 文案库选择回调
const closeChooseMaterial = async (data) => {
  console.log(data, "选择的文案");
  atherData.text = data[0].material_content;
};

defineExpose({
  open,
  close,
  getDetaile,
  styleList,
});
</script>

<template>
  <div class="content">
    <a-drawer
      :destroyOnClose="true"
      v-model:visible="state.visible"
      placement="right"
      :keyboard="true"
      width="50%"
      :closable="false"
      style="z-index: 200 !important"
      :maskClosable="false"
      :bodyStyle="{
        minWidth: '420px',
        paddingTop: 0,
      }"
      getContainer=".content"
      @close="drawerClose"
    >
      <slot name="title">
        <div class="title_box">
          <div class="title_top">
            <h1 class="title">AI生图</h1>
            <div class="close" @click="close">
              <CloseOutlined />
            </div>
          </div>
        </div>
      </slot>

      <a-spin
        :indicator="indicator"
        :spinning="state.spinning"
        tip="AI文案解析中..."
        class="spin_box"
        style="margin-top: 25%"
      >
        <!-- ai配图 -->
        <div class="content_item_box_ai_illustration">
          <span class="title"
            >绘图风格(当前选择风格：{{ selectCart_name || "无" }})</span
          >
          <Ai_style
            ref="Ai_styleRef"
            :aiModelList="props.aiModelList"
          ></Ai_style>
          <!-- <a-select ref="select" v-model:value="state.drawingStyleId" style="width: 200px" :options="styleList"
            placeholder="请选择绘图风格" allowClear></a-select> -->
        </div>

        <!-- 原始文案 -->
        <div class="old_text">
          <div class="old_text_title_box">
            <span class="title_old_text">原始文案</span>
            <div class="btn_box">
              <a-button type="primary" @click="reanalysis">场景解析</a-button>
              <a-button type="primary" @click="textImport('open')"
                >文案导入</a-button
              >
            </div>
          </div>
          <div class="old_text_content">
            <a-textarea
              v-model:value="atherData.text"
              placeholder="参考示例： &#10; 在这座城市的喧嚣背后，隐藏着一家时光穿梭机——‘光影记忆’电影院，今晚，就让我们一起推开这扇门，探寻那些被大银幕定格的梦幻瞬间。踏入大厅，仿佛穿越了时空隧道。每一面墙，都讲述着电影史上的辉煌篇章；每一个角落，都藏着等待你发现的小惊喜。 &#10; (按照句号/问号/感叹号可划分句子，每一句生成一个镜头画面)"
              :rows="6"
              allow-clear
            />
          </div>
        </div>

        <!-- 改写后文案 -->
        <div class="optimize_text">
          <span class="title">场景解析</span>
          <div class="optimize_text_content">
            <!-- 列表 -->
            <a-table
              bordered
              :dataSource="state.detailData?.text_splits"
              :columns="columns"
              class="table"
              :pagination="false"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <div style="display: flex; justify-content: space-around">
                    <a @click="editText(record)">编辑</a>
                    <a-popconfirm
                      title="确定删除此项吗?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="deletText(record.id)"
                      @cancel="cancel"
                      placement="topLeft"
                    >
                      <a>删除</a>
                    </a-popconfirm>
                  </div>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </a-spin>

      <template #footer>
        <div class="bottom_btn">
          <a-button style="margin-right: 15px" @click="close">取消</a-button>
          <a-button
            type="primary"
            @click="submitConfirm"
            :loading="state.spinning"
            >确定</a-button
          >
        </div>
      </template>
    </a-drawer>
  </div>

  <!-- 编辑文案弹窗 -->
  <EditAiText ref="EditAiTextRef" @editSubmit="getDetaile"></EditAiText>

  <!-- 文案库 -->
  <CopyLibraryModal
    ref="copyLibraryModal"
    selectType="radio"
    @importSuccess="closeChooseMaterial"
  />
</template>

<style lang="less" scoped>
.content {
  .title {
    font-size: 15px;
    margin: 25px 0 10px 0;
    color: #7f7f7f;
  }

  // 头部样式
  .title_box {
    width: calc(100% - 1px);
    //   padding-bottom: 10px;
    //   padding-top: 24px;
    padding: 10px 0;
    position: sticky;
    top: 0;
    z-index: 999;
    background-color: #fff;

    &::after {
      content: "";
      height: 1px;
      width: calc(100% + 48px);
      background-color: #e8e8e8;
      position: absolute;
      bottom: 0;
      left: -24px;
      z-index: 99;
    }

    .no-title {
      width: 25px;
      height: 39px;
      background-color: #fff;
      position: absolute;
      top: 30px;
      left: -25px;
    }

    //   .no-titles {
    //     width: 25px;
    //     height: 39px;
    //     background-color: #fff;
    //     position: absolute;
    //     top: 30px;
    //     right: -25px;
    //   }

    .title_top {
      display: flex;
      justify-content: space-between;
      color: #0c0d0e;
      align-items: center;

      // margin-bottom: 10px;
      h1 {
        font-size: 16px;
        font-weight: 600;
        //   margin-bottom: 4px;
        color: #0c0d0e;
      }

      .close {
        cursor: pointer;
        text-align: center;
        line-height: 29px;
        padding: 0 6px;
        width: 30px;
        height: 30px;

        &:hover {
          background-color: #f3f3f4;
        }
      }
    }

    .title_bottom {
      .btn_prev {
        border-radius: 5px;
        padding: 0 16px;
        font-size: 12px;
        height: 28px;
      }
    }
  }

  .bottom_btn {
    display: flex;
    justify-content: flex-end;
  }

  // 智能生图
  .content_item_box_ai_illustration {
    display: flex;
    flex-direction: column;
    // margin-top: 20px;

    .title {
      margin: 25px 0 10px 0;
    }
  }

  // 原始文案
  .old_text {
    display: flex;
    flex-direction: column;

    .old_text_title_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 25px;
      margin-bottom: 10px;

      .title_old_text {
        font-size: 15px;
        color: #7f7f7f;
      }
      .btn_box {
        display: flex;
        justify-self: end;
        gap: 10px;
      }
    }

    .old_text_content {
      :deep(.ant-input) {
        resize: none;
        padding-right: 14px;

        &::-webkit-scrollbar {
          height: 5px;
          /* 滚动条的高度 */
          width: 8px;
          // display: none;
        }

        &::-webkit-scrollbar-thumb {
          background: #888;
          /* 滑块的背景颜色 */
          border-radius: 10px;
          /* 滑块的圆角 */
        }

        &::-webkit-scrollbar-track {
          background: #f1f1f1;
          /* 轨道的背景色 */
          border-radius: 10px;
          /* 轨道的圆角 */
        }
      }
    }
  }

  // 改写后文案
  .optimize_text {
    display: flex;
    flex-direction: column;
  }
}
</style>
